var ns, WXPhotoPicker, bmLocation,trans;
var app = new Vue({
    el: '#app',
    data: {
        form: {
            ID: 0,
            DeviceName: '',
            DeviceNo: '',
            ProjectName: '',
            CheckTime: '',
            InChargeManName: '',
            CheckStatus: 1,
            TaskCompleteContent: '',
            GPSLocation: '',
        },
        //Type 1-观察  2-选择  3手动录入
        standardlist: [],
        imglist: [],
        maxuploadcount: CONFIG.maxuploadcount,
        standardStatus: 0,
        IsAllowWatermark:false,
        IsLoadWatermark:false,
        BtnShow:false,//异常操作按钮显示
        planform: {
            TaskStatus:1,
        },
    },
    methods: {
        get_data: function () {
            var that = this;
            var options = {};
            options.action = "getequipmenttaskdevicedata";
            options.ID = that.form.ID;
            // console.log(JSON.stringify(options));
            ns.post(options, function (succeed, data, err) {
                if (succeed) {
                    that.form = data.formdata;
                    that.planform.TaskStatus= data.formdata.PlanTaskStatus==undefined?that.form.TaskStatus: data.formdata.PlanTaskStatus;
                    that.standardlist = data.standardlist;
                    that.imglist = data.imglist;
                    that.getIsAllowWatermark();//获取是否只调用相机权限
                    that.StartBmap();//获取定位
                } else if (err) {
                    api.toast({
                        msg: err,
                        duration: 2000,
                        location: 'bottom'
                    });
                }
            }, {
                toast: true
            });
        },
        do_save: function () {
            var that = this;
            if (that.form.IsAllowUpload && that.imglist.length == 0) {
                api.toast({
                    msg: '请上传图片',
                    duration: 2000,
                    location: 'bottom'
                });
                return;
            }
            if (that.form.CheckStatus == 2) { //异常
                that.BtnShow = true;
                // api.confirm({
                //     title: '提示',
                //     msg: '当前结果异常,是否需要进行报事报修登记?',
                //     buttons: ['报事报修', '直接完成']
                // }, function (ret, err) {
                //     var ServiceStatus = -1;
                //     if (ret.buttonIndex == 1) {
                //         ServiceStatus = 1;
                //     } else if (ret.buttonIndex == 2) {
                //         ServiceStatus = 0;
                //     }
                //     if (ServiceStatus > -1) {
                //         that.do_save_process(ServiceStatus);
                //     }
                // });
                return;
            }
            that.do_save_process(0);
        },
        reload_list: function () {
            api.sendEvent({
                name: 'devicetaskcomplete',
            });
        },
        do_save_process: function (ServiceStatus) {
            var that = this;
            that.BtnShow = false;
            var options = {};
            options.action = "saveequipmenttaskdevicedata";
            options.ID = that.form.ID;
            options.standardlist = JSON.stringify(that.standardlist);
            options.CheckStatus = that.form.CheckStatus;
            options.GPSLocation = that.form.GPSLocation;
            options.ServiceStatus = ServiceStatus;
            options.TaskCompleteContent = that.form.TaskCompleteContent;
            var filelist = [];
            for (var i = 0; i < that.imglist.length; i++) {
                if (that.imglist[i].isupload) {
                    filelist.push(that.imglist[i].url);
                }
            }
            ns.post(options, function (succeed, data, err) {
                if (succeed) {
                    api.toast({
                        msg: '操作成功',
                        duration: 2000,
                        location: 'bottom'
                    });
                    that.reload_list();
                    api.addEventListener({
                        name: 'viewdisappear'
                    }, function (ret, err) {
                        api.closeWin();
                    });
                    if (ServiceStatus == 1) {
                        setTimeout(function(){
                            ns.openWin('neibubaoshi_add_frm', '内部报事',{
                                projectid:that.form.ProjectID,
                                name:that.form.ProjectName,
                            });
                        },500)
                        return
                    }
                    //保存设备维修工单
                    if (ServiceStatus == 2) {
                        setTimeout(function(){
                            ns.openWin('repairadd_frm', '设备维修',{
                                ProjectID:that.form.ProjectID,
                                ServiceID:that.form.DeviceID,//设备ID
                                ServiceName:that.form.DeviceName,
                                SourceType:that.form.PlanType==1?2:1,//1、2 PlanType设备巡检、维保
                            });
                        },500)
                        return
                    }
                    setTimeout(function () {
                        api.closeWin();
                    }, 300)
                } else if (err) {
                    api.toast({
                        msg: err,
                        duration: 2000,
                        location: 'bottom'
                    });
                }
            }, {
                toast: true,
                files: {
                    file: filelist
                }
            });
        },
        select_active: function (item, CheckStatus) {
            var that = this;
            if (that.planform.TaskStatus == 3) {
                return;
            }
            item.CheckStatus = CheckStatus;
            var isallnormal = true;
            for (var i = 0; i < that.standardlist.length; i++) {
                if (that.standardlist[i].CheckStatus == 2) {
                    isallnormal = false;
                }
            }
            if (isallnormal) {
                this.form.CheckStatus = 1;
                that.standardStatus = 1;
            } else {
                this.form.CheckStatus = 2;
                that.standardStatus = 2;
            }
        },
        select_all_active: function (CheckStatus) {
            var that = this;
            if (that.planform.TaskStatus == 3) {
                return;
            }
            that.standardStatus = 1;
            for (let index = 0; index < that.standardlist.length; index++) {
                if (that.standardlist[index].CheckStatus == 2) {
                    that.standardStatus = 2;
                    return;
                }
            }
            that.form.CheckStatus = CheckStatus;
        },
        choose_picture: function () {
            var that = this;
            //判断延迟，IsAllowWatermark值获取
            if (!that.IsLoadWatermark) {
                return;
            }
            setTimeout(function(){
                ns.confirmPer('camera', function () {
                    if (that.IsAllowWatermark) {
                        that.upload_choose_picture();
                    }
                    else {
                        that.choose_picture_start();
                    }
                })
            },300);
        },
        choose_picture_start:function(){
            var that = this;
            if (that.imglist.length >= that.maxuploadcount) {
                api.toast({
                    msg: '最多支持' + that.maxuploadcount + '张图片',
                    duration: 2000,
                    location: 'bottom'
                });
                return;
            }
            api.actionSheet({
                cancelTitle: '取消',
                buttons: ['拍照', '从相册选择']
            }, function(ret, err) {
                //拍照
                if(ret.buttonIndex==1){ 
                    that.upload_choose_picture();
                    return;
                }
                //从相册选择
                if(ret.buttonIndex==2){
                    that.choose_picture_album();
                    return;
                } 
                //取消 
                else{
                    return false;  
                }  
            });
        },
        choose_picture_album:function(){
            var that = this;
            WXPhotoPicker.open({
                max: that.maxuploadcount - that.imglist.length,
                type:'image',
            }, function(ret) {
                if (ret) {
                    if (ret.list.length > 0) {
                        ret.list.forEach((item) => {
                            that.do_imageFilter(item.path);
                            // that.imglist.push({
                            //     ID: 0,
                            //     url: item.path,
                            //     thumbPath: item.path,
                            //     isupload: true
                            // });
                        });
                    }
                }
            });
        },
        remove_img: function (index,item) {
            var that = this;
            that.imglist.splice(index, 1);
            if (item.ID > 0) {
                that.do_remove_uploadimg(item);
            }
        },
        do_remove_uploadimg: function (item) {
            var that = this;
            var options = {
                action: 'doremoveproductimg',
                ID: item.ID,
            }
            ns.post(options, function (succeed, data, err) { });
        },
        StartBmap: function () {
            var that = this;
            if (that.planform.TaskStatus == 3) {
                return;
            }
            ns.confirmPer('location', function () {
                that.StartLocation();
            })
        },
        StartLocation: function () {
            var that = this;
            if (that.planform.TaskStatus == 3) {
                return;
            }
            var num = 0; //次数
            that.form.GPSLocation = '';
            bmLocation.stopLocation();
            bmLocation.singleLocation({
                reGeocode: true,
                netWorkState: true
            }, function (ret) {
                if (ret.status) {
                    var locationDescribe=ns.DealLocationDescribe(ret.reGeo.locationDescribe);
                    that.form.GPSLocation = ret.reGeo.province + ret.reGeo.city +
                        ret.reGeo.district + ret.reGeo.street + ret.reGeo.streetNumber + locationDescribe;
                    // if (ret.reGeo.poiList != undefined && ret.reGeo.poiList.length > 0) {
                    //     that.form.GPSLocation = ret.reGeo.province + ret.reGeo.city +
                    //         ret.reGeo.district + ret.reGeo.street + ret.reGeo.poiList[0].name;
                    // }
                }
            });
        },
        configManager: function () {
            bmLocation.configManager({
                // accuracy: 'hight_accuracy',
                filter: 1,
                activityType: 'automotiveNavigation',
                coordinateType: 'BMK09LL',
                locationTimeout: 10,
                reGeocodeTimeout: 10
            });
        },
        do_viewimages: function (activeIndex) {
            var that = this;
            var imageUrls = [];
            for (var i = 0; i < that.imglist.length; i++) {
                imageUrls.push(that.imglist[i].url);
            }
            var imageBrowser = api.require('imageBrowser');
            imageBrowser.openImages({
                showList: false,
                activeIndex: activeIndex,
                imageUrls: imageUrls
            });
        },
        //获取是否只调用相机权限
        getIsAllowWatermark:function(){
            var that = this;
            if (!that.form.ProjectID) {
                return;
            }
            var options = {
                action: 'getplanparam',
                ProjectID: that.form.ProjectID,
                ConfigKey: 'SBGLPhotoUse'
            };
            that.IsLoadWatermark=false;
            ns.post(options, function (succeed, data, err) {
                that.IsLoadWatermark=true;
                if (succeed) {
                    that.IsAllowWatermark = data.type == 2 ? true : false;  
                }
            });
        },
        // 系统只调用相机 并添加水印
        upload_choose_picture:function(){
            var that = this;
            api.getPicture({
                sourceType: 'camera',
                encodingType: 'jpg',
                destinationType: 'url',
                allowEdit: false,
                saveToPhotoAlbum: that.IsAllowWatermark?false:true,
            }, function(ret, err) {
                if (ret&&ret.data) {
                    that.do_imageFilter(ret.data);
                    // if (that.IsAllowWatermark) {
                    //     that.waterMark(ret.data);
                    //     return;
                    // }
                    // else {
                    //     that.imglist.push({
                    //         ID: 0,
                    //         url: ret.data,
                    //         thumbPath: ret.data,
                    //         isupload: true
                    //     });
                    // }
                } 
            });
        },
        waterMark: function (imagePath) {
            var that = this;
            if(!imagePath){
                api.toast({
                    msg: '图片地址为空',
                    duration: 2000,
                    location: 'bottom'
                });
                return;
            } 
            var imageName =imagePath.split('/').pop(); //获取图片名称
            var dateTime = moment().format('YYYY-MM-DD HH:mm:ss');
            // 调用生成水印方法  返回Base64图片格式
            ns.setWatermark(imagePath, '设备管理水印', dateTime, that.form.GPSLocation).then((value) => {
                var base64Str=value;
                if (base64Str) {
                    //Base64图片 转jpg、png格式
                    trans.saveImage({
                        base64Str: base64Str,
                        // album:true,
                        imgPath: "fs://watermark/",
                        imgName: imageName
                    }, function (ret, err) {
                        if (ret.status) {
                            var newImagePath = api.fsDir + '/' + 'watermark' + '/' + imageName;
                            that.imglist.push({
                                ID: 0,
                                url: newImagePath,
                                thumbPath: newImagePath,
                                isupload: true
                            });
                             //水印图片-保存到相册
                            api.saveMediaToAlbum({
                                path: 'fs://watermark/' + imageName
                            }, function (ret, err) {
                            });
                        } else {
                            api.toast({
                                msg: '水印图片保存本地失败！',
                                duration: 2000,
                                location: 'bottom'
                            });
                            return;
                        }
                    });
                }else{
                    // api.toast({
                    //     msg: '生成水印失败！',
                    //     duration: 2000,
                    //     location: 'bottom'
                    // });
                    that.imglist.push({
                        ID: 0,
                        url: imagePath,
                        thumbPath: imagePath,
                        isupload: true
                    });
                    return;
                }   
            }) 
        },
             //图片压缩
             do_imageFilter:function(path){
                var that=this;
                var imgName = Date.now() + '.jpg';
                var target_w = 500;
                var imageFilter = api.require('imageFilter');
                imageFilter.getAttr({
                    path: path
                }, function(ret, err) {
                    if (ret.status) {
                        if (ret.width < target_w) {
                            target_w = ret.width;
                        }
                        var original_w = ret.width;
                        var original_h = ret.height;
                        var scale = original_w / target_w;
                        var target_h = Math.round(original_h / scale);
                        imageFilter.compress({
                            img: path,
                            quality: 1,
                            size: {
                                w: target_w,
                                h: target_h
                            },
                            save: {
                                album: false,
                                imgPath: api.cacheDir + '/upload/',
                                imgName: imgName
                            }
                        }, function(ret, err) {
                            if (ret.status) {
                                var imgFullName=api.cacheDir + '/upload/' + imgName;
                                if (that.IsAllowWatermark) {
                                    that.waterMark(imgFullName);
                                    return;
                                }
                                else {
                                    that.imglist.push({
                                        ID: 0,
                                        url: imgFullName,
                                        thumbPath: imgFullName,
                                        isupload: true
                                    });
                                }
                            }else{
                                alert( JSON.stringify( err ) );
                            }
                        });
                    }
                });
            },
    }
});
apiready = function () {
    api.parseTapmode();
    WXPhotoPicker = api.require('WXPhotoPicker');
    bmLocation = api.require('bmLocation');
    trans = api.require('trans');
    ns = window.Foresight.Util;
    toast = new auiToast();
    app.form.ID = api.pageParam.id || 0;

    setTimeout(function () {
        app.get_data();
    }, 1000)
    setTimeout(function () {
        app.configManager();
        // app.StartBmap();
    }, 1000)
    bmLocation.setAgreePrivacy({
        agree: true
    });   
}
